define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
     require('echarts/chart/pie');
    var zrUtil = require('zrender/tool/util');
    var zrnumber = require('echarts/util/number');

    var cate=['黄页','招聘','房产','二手','二手车'];
    var index=['总体','精准','置顶'];
    var cache={};

    var productName={
    	"zhineng":"智能",
    	"jingzhun":"精准",
    	"zhiding":"置顶",
    	"all":"总体"
    };

     var chart_pie = ec.init(document.getElementById('pie'));

    var chart_bar=ec.init(document.getElementById('bar'));

        var chart_bar0=ec.init(document.getElementById('bar0'));


//饼图的数据模版
var option_pie_one=    {
	title : {
                text: '',
                x:'center',
                y:'380'
            },
        tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        x : 'left',
        data:cate
    },
        calculable : true,
    series : [
        {
            name:'',
            type:'pie',
            radius : '55%',
            center: ['50%', 225],
            data:[]
        }
    ]
    };

 //带timeline的饼图模版   
var option_pie = {
    timeline : {
    type:"number",
    symbolSize:3,
        x:"1%",
        x2:"1%",
        width:"100%",
        label:{
                interval: 'auto',
                formatter:function(param){
                	    var dateGrp = $('#totalOption').attr('dateGrp');
    if(dateGrp=='quarter'){
    return param.substr(0,4)+"Q"+param.substr(5,1);
    }
    		return param;
    	}
        },
        data : ['']
    },
    options:[]
};

var option_bar = {
    timeline : {
    	show:false,
        data : ['']
    },
    options:[]
};

var option_bar_one = {
	title : {
                text: '差额百分比',
                link:'http://wiki.58corp.com/index.php?title=%E6%94%B6%E5%85%A5%E7%9C%8B%E6%9D%BF%E6%8C%87%E6%A0%87',
                subtext:'',
                subtextStyle:{
                	color:'blue'
                }
            },
    tooltip : {
        trigger: 'axis',
        formatter:"{b}<br>{a}：{c}%<br>{a1}：{c1}%<br>{a2}：{c2}%<br>{a3}：{c3}%<br>{a4}：{c4}%"
    },
    legend: {
        data:cate
    },
    calculable : true,
    xAxis : [
        {
            type : 'category',
            data : index
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : []
};

var option_bar0 = {
	title : {
                text: '预估完成率',
                link:'http://wiki.58corp.com/index.php?title=%E6%94%B6%E5%85%A5%E7%9C%8B%E6%9D%BF%E6%8C%87%E6%A0%87',
                subtext:'',
                subtextStyle:{
                	color:'blue'
                }
            },
    tooltip : {
        trigger: 'axis',
        formatter:function(param){
        	// console.log(param);
        	var result='<table class="table-center">'
        	result+="<tr><td>"+param[0][1]+"</td><td>预估</td><td>实际</td></tr>";

        	result+="<tr><td>"+productName[param[4].series.stack]+"</td>"
        	result+="<td>"+((Number(param[4].value)+Number(param[5].value)).toFixed(2))+"%</td>";
        	result+="<td>"+param[5].value+"%</td><tr>";
        	
        	        	result+="<tr><td>"+productName[param[2].series.stack]+"</td>"
        	result+="<td>"+((Number(param[2].value)+Number(param[3].value)).toFixed(2))+"%</td>";
        	result+="<td>"+param[3].value+"%</td><tr>";

        	result+="<tr><td>"+productName[param[0].series.stack]+"</td>"
        	result+="<td>"+((Number(param[0].value)+Number(param[1].value)).toFixed(2))+"%</td>";
        	result+="<td>"+param[1].value+"%</td><tr>";



        	result+="</table>";
        	return result;
        }
    },
        legend: {
        data:['总体时间','当前进度','预估','实际'],
        selectedMode:false
    },
    calculable : true,
    xAxis : [
        {
            type : 'category',
            data : cate
        }
    ],
    yAxis : [
        {
            type : 'value',
            scale:true
        }
    ],
    series : [
            {
                name:'总体时间',
                type:'line',
                symbol:'none',
                data:[0],
            markLine: {
                            clickable:false,
                data: [
                [
                  {name: '',value:'',yAxis:100,xAxis:-1},
        {name: '',value:'',yAxis:100,xAxis:6}
      
                ]
                ]
            }
        },
         {
                name:'当前进度',
                type:'line',
                symbol:'none',
                data:[0],
            markLine: {
                            clickable:false,
                data: [
                                [
                                {name: '',value:'',yAxis:0,xAxis:-1},
        {name: '',value:'',yAxis:0,xAxis:6}
     
                ]
                ]
            }
        }
    ]
};

var option_mutibar_one = {
	grid:{
		x:'30%',
		x2:'7%',
	},
    title : {
        text: '',
        subtext: '',
        x:'left'
    },
    tooltip : {
        trigger: 'axis',
        formatter:function(param){
           var result=param[0][1]+"<br>";
           result+=param[0].seriesName+"："+param[0].value+"%<br>";
           result+=param[1].seriesName+"："+((Number(param[0].value)+Number(param[1].value)).toFixed(2))+"%";
           return result;            
        }
    },
    calculable : true,
    xAxis : [
        {
            type : 'value',
             position:'top',
            splitNumber:2
        }
    ],
    yAxis : [
        {
            type : 'category',
            data : cate,
            axisLabel:{
            	margin:2,
            	textStyle:{
            		fontSize:1
            	}
            }
        }
    ],
        legend: {
        data:['总体时间','当前进度'],
        itemWidth:10,
        itemHeight:5,
        orient:'vertical',
        x:'right',
        textStyle:{
            fontSize:4
        },
        selectedMode:false
    },
    series : [
            {
            name:'实际',
            type:'bar',
            stack: 'sum',
            itemStyle: {
                normal: {
                    color: 'gray',
                    barBorderColor: 'tomato',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            },
            data:[]
        },
        {
            name:'预估',
            type:'bar',
            stack: 'sum',
            itemStyle: {
                normal: {
                    color: 'tomato',
                    barBorderColor: 'tomato',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            },
            data:[]
        },
        {
                name:'总体时间',
                type:'line',
                symbol:'none',
                data:[0],
            markLine: {
                            clickable:false,
                data: [
                [
        // {name: '',xAxis:0,yAxis:100},                
        // {name: '',xAxis:6,yAxis:100}
                ]
                ]
            }
        },
                {
                name:'当前进度',
                type:'line',
                symbol:'none',
                data:[0],
            markLine: {
                            clickable:false,
                data: [
                                [
        {name: '',value:'',xAxis:0,yAxis:6},
        {name: '',value:'',xAxis:0,yAxis:-1}
                ]
                ]
            }
        }
    ]
};


var model={
            name:'实际',
            type:'bar',
            stack: 'sum',
            itemStyle: {
                normal: {
                    color: 'gray',
                    barBorderColor: 'tomato',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            },
            data:[]
        };
   var model_sub={
            name:'预估',
            type:'bar',
            stack: 'sum',
            itemStyle: {
                normal: {
                    color: 'tomato',
                    barBorderColor: 'tomato',
                    barBorderWidth: 6,
                    barBorderRadius:0,
                    label: {
                        show: true,
                        position: 'top',
                        textStyle:{
                        	color:'orange',
                        	fontSize:5
                        },
                        formatter: function(param){
                        	return productName[param.series.stack];
                        }
                    }
                }
            },
            data:[]
        };

//设置右上角多个柱状图
// function setMutiBar(data){
// 	var time=data.timeline[data.timeline.length-1];
// 	allData=data.options[time].product
// 	$.each(allData,function(product,array){
// 	         var option=zrUtil.clone(option_mutibar_one)
//                    option.title.text="预估完成率";
//                    option.title.textStyle={fontSize: 10};
//                    option.title.link="http://wiki.58corp.com/index.php?title=%E6%94%B6%E5%85%A5%E7%9C%8B%E6%9D%BF%E6%8C%87%E6%A0%87";
// 	         option.title.subtext=productName[product];
// 	         var name=data.timeline[data.timeline.length-1];
//                      option.series[0].data=data.options[name].complete_rate;
//                      var mins=[];
//                      $.each(data.options[name].complete_rate,function(index,comp_s){
//                         mins.push((data.options[name].fore_rate[index]-comp_s).toFixed(2));
//                      });
//                     option.series[1].data=mins;
//                     var time=(data.options[name].time_rate*100).toFixed(2);
//                     option.series[3].markLine.data[0][0].xAxis=time;
//                     option.series[3].markLine.data[0][1].xAxis=time;
//                                         option.series[3].markLine.data[0][0].value=time;
// 	         // option.series.push({"name":"完成","type":"bar","data":data.options[name].complete_rate});
// 	         // option.series.push({"name":"预期","type":"bar","data":data.options[name].fore_rate});
// 	var chart_mutilbar=ec.init(document.getElementById(product));
//              chart_mutilbar.setOption(option);

// 	});

// }

    $("#busiTypeDetail").change(function(){
    	var cur_index=chart_pie.component.timeline.currentIndex;
    	showPieDetail(cache.timeline[cur_index],$("#busiTypeDetail").val());
    });

// var pieTableHead_month='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当月任务</th><th>实际进度</th><th>完成所需日均额度</th><th>当前实际日均收入</th><th>差额百分比</th><th>预估完成率</th></tr>';
// var pieTableHead_quarter='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当季度任务</th><th>实际进度</th><th>完成所需日均额度</th><th>当前实际日均收入</th><th>差额百分比</th><th>预估完成率</th></tr>';
var pieTableHead_month='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当前实际日均收入</th></tr>';
var pieTableHead_quarter='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当前实际日均收入</th></tr>';

//显示某个时间的饼图详细数据
function showPieDetail(time,busi){
    if(!cache||!cache.options||!cache.options[time]){
        console.log("无缓存数据");
    }
    var data=cache.options[time].product[busi];
    var dataSort=sortByName(data);
    $('#pieDetail thead').text("");
    var dateGrp = $('#totalOption').attr('dateGrp');
    if(dateGrp=='month'){
    $('#pieDetail thead').append(pieTableHead_month);
    }else if (dateGrp=='quarter') {
        $('#pieDetail thead').append(pieTableHead_quarter);
    };

        $('#pieDetail tbody').text("");
                    $.each(dataSort,function(index,value){
                    $('#pieDetail tbody').append("<tr></tr>");
                    $('#pieDetail tbody tr:last').append(addInfo(value.businessTypeName));
                     $('#pieDetail tbody tr:last').append(addInfo(value.cash));
                    $('#pieDetail tbody tr:last').append(addInfo(value.cash_chain));
                     $('#pieDetail tbody tr:last').append(addInfo(value.cash_YoY));
                     // $('#pieDetail tbody tr:last').append(addInfo(value.task));
                     // $('#pieDetail tbody tr:last').append(addInfo4(value));
                     // $('#pieDetail tbody tr:last').append(addInfo(value.avg_task));
                     $('#pieDetail tbody tr:last').append(addInfo(value.avg_complete));
                     // $('#pieDetail tbody tr:last').append(addInfo2(-value.avg_bal));
                     // $('#pieDetail tbody tr:last').append(addInfo3(value.fore_rate));
                    });

}

function addInfo4(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value.complete_rate)){
        var ss=value.complete_rate+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if((value.complete_rate-value.time_rate*100)>0){
                td.addClass('text-danger');
                td.html(ss);
            }else{
                td.addClass('text-success');
                td.html(ss);
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value.complete_rate));
        }
    }
    return td.html(value.complete_rate);
}

function addInfo3(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value)){
        var ss=value+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if(value>100){
                td.addClass('text-danger');
                td.html(ss);
            }else{
                td.addClass('text-success');
                td.html(ss);
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value));
        }
    }
    return td.html(value);
}

function addInfo2(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value)){
        var ss=value+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if(value>0){
                td.addClass('text-danger');
                td.html(ss);
            }else{
                td.addClass('text-success');
                td.html(ss);
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value));
        }
    }
    return td.html(value);
}

function addInfo(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value)){
        var ss=value+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if(value>0){
                td.addClass('text-danger');
                td.html(ss);
                td.append('<i class="upi"></i>');
            }else{
                td.addClass('text-success');
                td.html(ss);
                td.append('<i class="downi"></i>');
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value));
        }
    }
    return td.html(value);
}


function sortByName(data){
	if(!data)return [];
	var aa={};
	$.each(data,function(index,value){
		aa[value.businessTypeName]=value;
	});
	var resut=[];
	$.each(cate,function(index,value){
		resut.push(aa[value]);
	});
	return resut;
}

        var temp=['huangye','zhaopin','fangchan','ershou','ershouche'];

function sortByName2(data){
        if(!data)return [];
    var resut=[];
    $.each(temp,function(index,value){
        resut.push(data[value]);
    });
    return resut;
}

function sortBy(array,sort_array,filedName){
	if(!array)return [];
	var aa={};
	$.each(array,function(index,value){
		aa[value[filedName]]=value;
	});
	var resut=[];
	$.each(sort_array,function(index,value){
		resut.push(aa[value]);
	});
	return resut;
}

         function formatShowDate(yyyymmdd){
        var dateGrp = $('#totalOption').attr('dateGrp');
        if('day'==dateGrp){
            return yyyymmdd.substr(0,4)+"-"+yyyymmdd.substr(4,2)+"-"+yyyymmdd.substr(6,2);
        }else if('quarter'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(5,1)+"季度";
        }else if('month'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
}


//设置饼图数据
function setPie(data){
                    option_pie.options=[];
                    //饼图时间轴
                    option_pie.timeline.data=data.timeline;
                    option_pie.timeline.currentIndex=data.timeline.length-1;
                    //饼图数据
                    $.each(data.options,function(index,value){
                        var option= zrUtil.clone(option_pie_one);
                        option.series[0].name=index;
                        $.each(value.product.all,function(i,v){
                            option.series[0].data.push({"name":v.businessTypeName,"value":v.cash});
                        });
                        option.title.text=formatShowDate(index);
                        option_pie.options.push(option);
                    });
                     chart_pie.setOption(option_pie,true);
                     chart_pie.hideLoading();
                     showPieDetail(data.timeline[data.timeline.length-1],$("#busiTypeDetail").val());
}

//设置右下角柱状图
function setBar(data){
                    option_bar.options=[];
                    //柱形图时间轴
                    option_bar.timeline.data=data.timeline;
                    option_bar.timeline.currentIndex=data.timeline.length-1;
                    //柱形图数据
                    $.each(data.options,function(time,value){
                        var option=zrUtil.clone(option_bar_one);
                         option.title.subtext=formatShowDate(time);
                         var sort1=sortByName2(value.business);
                    $.each(sort1,function(index,value_in){
                        var ss=[];
                        var sort=sortBy(value_in,option.xAxis[0].data,'productTypeName');
                        $.each(sort,function(indx,val){
                            ss.push(-val.avg_bal);
                        });
                        option.series.push({"name":value_in[0].businessTypeName,"type":"bar","data":ss});
                    });
                        option_bar.options.push(option);
                    });
                    chart_bar.setOption(option_bar,true);
                    chart_bar.hideLoading();
}

function setBar0(data){
    var time=data.timeline[data.timeline.length-1];
    var value=data.options[time];

     var option=zrUtil.clone(option_bar0)
     option.title.text="预估完成率";
     option.title.subtext="数据截止日期("+value.product.all[0].stat_date+")";
                   
                   $.each(value.product,function(productName,value_in){
                    if(productName=='zhineng')return;
                        var ss=[];
                        var mins=[];
                        var sort=sortBy(value_in,option.xAxis[0].data,'businessTypeName');
                        $.each(sort,function(indx,val){
                            ss.push(val.complete_rate);
                            mins.push((val.fore_rate-val.complete_rate).toFixed(2));
                        });
                        var ser=zrUtil.clone(model);
                        ser.stack=productName;
                        ser.data=ss;
                        option.series.push(ser);

                        var ser_sub=zrUtil.clone(model_sub);
                        ser_sub.stack=productName;
                        ser_sub.data=mins;
                        option.series.push(ser_sub);
                    });

                    var current_time=(value.product.all[0].time_rate*100).toFixed(2);
                    option.series[1].markLine.data[0][0].yAxis=current_time;
                    option.series[1].markLine.data[0][1].yAxis=current_time;
                    option.series[1].markLine.data[0][0].value=current_time;
                     option_bar.options.push(option);
                     chart_bar0.setOption(option);
                     chart_bar0.hideLoading();
}


function showPie(type){
    chart_pie.showLoading({
            text: '正在努力的读取数据中...'
    });
    // chart_bar.showLoading({
    //         text: '正在努力的读取数据中...'
    // });
    // chart_bar0.showLoading({
    //         text: '正在努力的读取数据中...'
    // });
    $.ajax({
        url: '/dashboard/income/ajax/getKpiByBusiness',
        type: 'POST',
        async: true,
        data:{"type":type},
        dataType: 'json',
        success: function(data) {
            cache=data;
            // console.log(data);
            //设置饼图
            setPie(data);
            // setBar(data);  //setMutiBar(data);
            // setBar0(data);
             // chart_pie.connect(chart_bar);
             // chart_bar.connect(chart_pie);

             //timeline联动
             chart_pie.on("timelineChanged", function(param){
                showPieDetail(param.data,$("#busiTypeDetail").val());
                // chart_bar.component.timeline.play(param.currentIndex,false);
             });            
        },
        timeout: 30000,
        error: function() {
        }
    });
}


var returnObj={
    showPie:showPie
};
return returnObj;
});